import { useState, ReactText, useRef, useEffect } from 'react';
import { useForm } from '@formily/react';
import { getMessage, TextWidget } from '@inbiz/react';
import { uuid } from '@inbiz/utils';
import { Field } from '@formily/core';
import { Button, Modal, Radio, Form, Select, message } from 'antd';
import moment from 'moment';
import TableBox from './TableBox';
import SourceForm from './SourceForm';
import './configModal.less';

type IProps = {
  className?: '';
  value: any;
  onChange?: (value: any) => void;
};

type SourceDataType = {
  key: string;
  value: string;
  splitJoint: string;
  status: boolean;
};

type FormValueType = {
  timeStatus: boolean;
  recordNum: number | undefined;
  timeKey: string | undefined;
  contentKey: { [key: string]: any }[] | undefined;
};
export interface DataType {
  id: ReactText;
  time: string;
  content: string;
  active?: boolean;
}

const { Option } = Select;

const ConfigDialog = (props: IProps) => {
  const { className = `inbiz-TimeLine-config`, onChange } = props;
  const globalForm = useForm();
  const [form] = Form.useForm();

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [source, setSource] = useState(1);

  const [selectValue, setSelectValue] = useState<string>(props.value?.selectValue || 'YYYY');
  const sourceModel = globalForm.query(/sourceModel$/).take() as Field;

  const [sourceData, setSourceData] = useState<SourceDataType[]>(
    props.value.formValue.contentKey || [
      {
        key: uuid(0, 16),
        value: undefined,
        splitJoint: undefined,
        status: false,
      },
    ],
  );

  const [formValue, setFormValue] = useState<FormValueType>(
    props.value?.formValue || {
      timeStatus: false,
      recordNum: 10,
      timeKey: undefined,
      contentKey: sourceData,
    },
  );

  const selectDataSource = [
    { label: 'YYYY', value: 'YYYY' },
    { label: 'YYYY-MM', value: 'YYYY-MM' },
    { label: 'YYYY-MM-DD', value: 'YYYY-MM-DD' },
  ];

  /**
   * 数据回显
   * 回显表格和表单的配置数据
   */
  const showModal = () => {
    setIsModalVisible(true);
  };

  /**
   * 配置完成，提交数据
   * 1-静态数据源：校验通过后获取并提交表格的配置数据
   * 2-动态数据源：校验通过后获取并提交表单的配置数据
   */
  const handleOk = async () => {
    if (source === 1) {
      tableRef.current?.getData().then((res: { time: any }[]) => {
        // console.log('res', res)
        const data = res.sort((a, b) => {
          return moment(a.time).valueOf() - moment(b.time).valueOf();
        });
        onChange &&
          onChange({
            source,
            sourceModel: sourceModel?.value,
            tableData: data,
            formValue: {},
            selectValue,
          });
        setIsModalVisible(false);
      });
    } else {
      if (!formValue.timeKey) {
        setFormValue((item) => {
          let oldItem = { ...item };
          oldItem.timeStatus = true;
          return oldItem;
        });
        return;
      }
      let statusArr = sourceData
        .map((item, index) => {
          if (!item.value) {
            return index;
          }
          return undefined;
        })
        .filter((v) => v !== undefined);
      if (statusArr.length) {
        setSourceData((source) => {
          let oldSource = [...source];
          statusArr.forEach((item) => {
            oldSource[item!].status = true;
          });
          return oldSource;
        });
        return;
      }
      onChange &&
        onChange({
          source,
          sourceModel: sourceModel?.value,
          tableData: [],
          formValue: { ...formValue, contentKey: [...sourceData] },
        });
      setIsModalVisible(false);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  /**
   * 切换数据源选项
   * 需要切换的数据源是动态数据时进行模型配置校验，校验通过显示数据配置表单
   * 选择数据源是静态数据时显示数据配置表格
   */
  const onRadioChange = (e: any) => {
    //@ts-ignore
    if (!globalForm.fields['form.senior.soure.x-component-props.sourceModel']?.value) {
      message.warn(getMessage('TimeLine.tips.pleaseChoseQuerySource'));
      return;
    }
    setSource(e.target.value);
  };

  useEffect(() => {
    if (isModalVisible) {
      setSource(props.value?.source || 1);
      form.setFieldsValue(props.value.formValue);
      setFormValue(props.value.formValue);
      setSourceData(
        props.value.formValue.contentKey || [
          {
            key: uuid(0, 16),
            value: undefined,
            splitJoint: undefined,
            status: false,
          },
        ],
      );
    }
  }, [props.value, isModalVisible]);

  const tableRef = useRef<{
    // 获取数据， 会触发校验
    getData: () => Promise<[]>;
    // 主动校验
    valid: () => Promise<Object>;
    // 更新内部数据
    updateSource: (id: string, data: object) => boolean;
  }>();

  useEffect(() => {
    setFormValue((v) => {
      let oldV = { ...v };
      oldV.contentKey = sourceData;
      return oldV;
    });
  }, [sourceData]);

  return (
    <div>
      <Button type="primary" onClick={showModal}>
        <TextWidget>TimeLine.config</TextWidget>
      </Button>
      <Modal
        title={getMessage('TimeLine.config')}
        okText={getMessage('TimeLine.btn.ok')}
        cancelText={getMessage('TimeLine.btn.cancel')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        destroyOnClose
        width={800}
      >
        <div className={className}>
          <div className={`${className}-source`}>
            <div className="item-label">
              <TextWidget>TimeLine.dataType</TextWidget>
            </div>
            <div className="item-radio">
              <Radio.Group onChange={onRadioChange} value={source}>
                <Radio value={1}>
                  <TextWidget>TimeLine.staticData</TextWidget>
                </Radio>
                <Radio value={2}>
                  <TextWidget>TimeLine.dynamicData</TextWidget>
                </Radio>
              </Radio.Group>
            </div>
          </div>
          {source === 1 ? (
            <div className="selectFormat">
              <div className="formatText">
                <TextWidget>TimeLine.dateFormate</TextWidget>
              </div>
              <Select
                value={selectValue}
                onChange={(value) => setSelectValue(value)}
                className="selectOption"
              >
                {selectDataSource.map((item) => (
                  <Option key={item.value} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </div>
          ) : null}

          {source === 1 ? (
            <div className={`${className}-static`}>
              <TableBox ref={tableRef} value={props.value.tableData} />
            </div>
          ) : (
            <div className="form-box">
              <SourceForm
                globalForm={globalForm}
                sourceData={sourceData}
                setSourceData={setSourceData}
                formValue={formValue}
                setFormValue={setFormValue}
              />
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default ConfigDialog;
export type { SourceDataType, FormValueType };
